package cn.hqu.day01;

import org.apache.spark.SparkConf;
import org.apache.spark.SparkContext;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.FlatMapFunction;
import org.apache.spark.api.java.function.Function;
import org.apache.spark.api.java.function.Function2;
import org.apache.spark.api.java.function.PairFunction;
import org.apache.spark.rdd.RDD;
import scala.Tuple2;

import java.util.Arrays;
import java.util.Iterator;

public class JavaWordCount {

    public static void main(String[] args) {
        SparkConf conf = new SparkConf().setAppName("java wordcount");
        // JavaSparkContext是对SparkContext的包装
        JavaSparkContext jsc = new JavaSparkContext(conf);

        // JavaSparkContext可以创建JavaRDD
        // JavaRDD包装了RDD
        JavaRDD<String> lines = jsc.textFile(args[0]);

        // 切分压平
        JavaRDD<String> words = lines.flatMap(new FlatMapFunction<String, String>() {
            @Override
            public Iterator<String> call(String line) throws Exception {
                return Arrays.stream(line.split(" ")).iterator();
            }
        });

        // 将单词和1组合（word,1）
//        JavaRDD<Tuple2<String, Integer>> wordAndOne = words.map(new Function<String, Tuple2<String, Integer>>() {
//            @Override
//            public Tuple2<String, Integer> call(String word) throws Exception {
//                return Tuple2.apply(word, 1);
//            }
//        });

        JavaPairRDD<String, Integer> wordAndOne = words.mapToPair(new PairFunction<String, String, Integer>() {
            @Override
            public Tuple2<String, Integer> call(String word) throws Exception {
                return Tuple2.apply(word, 1);
            }
        });


        // 聚合
        JavaPairRDD<String, Integer> reduced = wordAndOne.reduceByKey(new Function2<Integer, Integer, Integer>() {
            @Override
            public Integer call(Integer v1, Integer v2) throws Exception {
                return v1 + v2;
            }
        });

        // 交换顺序
        JavaPairRDD<Integer, String> swaped = reduced.mapToPair(new PairFunction<Tuple2<String, Integer>, Integer, String>() {
            @Override
            public Tuple2<Integer, String> call(Tuple2<String, Integer> tp) throws Exception {
                return tp.swap();
            }
        });

        // 排序
        JavaPairRDD<Integer, String> sorted = swaped.sortByKey(false);

        // 再交换顺序
        JavaPairRDD<String, Integer> result = sorted.mapToPair(new PairFunction<Tuple2<Integer, String>, String, Integer>() {
            @Override
            public Tuple2<String, Integer> call(Tuple2<Integer, String> tp) throws Exception {
                return tp.swap();
            }
        });

        // 保存到HDFS
        result.saveAsTextFile(args[1]);

        // 关闭sc
        jsc.stop();

    }
}
